const jsQR = require("./jsQR.js"); // 引入 jsQR

Page({
  data: {
    currentTab: "scan", // 当前功能模式
    showCamera: true, // 是否显示摄像头
    imagePath: null, // 拍摄的照片路径
    scanResult: null, // 扫码结果
    isScanning: false, // 是否正在扫码
    scanLineAnimation: null,
  },

  onLoad() {
    wx.authorize({
      scope: "scope.camera",
      success: () => {
        console.log("摄像头权限已授权");
        this.startScan();
      },
      fail: (err) => {
        console.error("摄像头权限未授权", err);
        wx.showToast({
          title: "请授权摄像头权限",
          icon: "none",
        });
      },
    });
    this.createScanLineAnimation();
  },
  // 添加新方法
  createScanLineAnimation() {
    const animation = wx.createAnimation({
      duration: 2000,
      timingFunction: "linear",
    });
    this.animation = animation;
    this.restartScanLineAnimation();
  },

  restartScanLineAnimation() {
    this.animation.top("20%").step();
    this.animation.top("80%").step();
    this.setData({
      scanLineAnimation: this.animation.export(),
    });
  },

  // 开始扫码
  startScan() {
    if (this.data.currentTab !== "scan" || this.data.isScanning) return;

    this.setData({ isScanning: true });
    this.scanFrame();
  },

  // 扫码逻辑
  scanFrame() {
    if (!this.data.isScanning) return;

    const ctx = wx.createCameraContext();
    ctx.takePhoto({
      quality: "normal",
      success: (res) => {
        const tempFilePath = res.tempImagePath;

        wx.getImageInfo({
          src: tempFilePath,
          success: (imageInfo) => {
            const canvasCtx = wx.createCanvasContext("scanCanvas");
            canvasCtx.drawImage(tempFilePath, 0, 0, 300, 300);
            canvasCtx.draw(false, () => {
              wx.canvasGetImageData({
                canvasId: "scanCanvas",
                x: 0,
                y: 0,
                width: 300,
                height: 300,
                success: (res) => {
                  const imageData = {
                    data: new Uint8ClampedArray(res.data),
                    width: res.width,
                    height: res.height,
                  };

                  const code = jsQR(
                    imageData.data,
                    imageData.width,
                    imageData.height
                  );
                  if (code) {
                    console.log("扫描结果:", code.data);
                    this.setData({
                      scanResult: code.data,
                      isScanning: false,
                    });
                    wx.showToast({
                      title: "扫码成功",
                      icon: "success",
                    });
                  } else {
                    // 未识别到二维码，继续扫描
                    setTimeout(() => this.scanFrame(), 500);
                  }
                },
                fail: (err) => {
                  console.error("获取图像数据失败", err);
                  this.setData({ isScanning: false });
                },
              });
            });
          },
          fail: (err) => {
            console.error("获取图片信息失败", err);
            this.setData({ isScanning: false });
          },
        });
      },
      fail: (err) => {
        console.error("拍照失败", err);
        this.setData({ isScanning: false });
      },
    });
  },

  // 切换功能模式
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      currentTab: tab,
      imagePath: null,
      scanResult: null,
      isScanning: tab === "scan", // 切换模式时重置扫码状态
    });

    if (tab === "scan") {
      this.startScan();
    }
  },

  // 拍照功能
  takePhoto() {
    const ctx = wx.createCameraContext();
    ctx.takePhoto({
      quality: "high",
      success: (res) => {
        this.setData({
          imagePath: res.tempImagePath,
          showCamera: false,
        });

        if (this.data.currentTab === "calorie") {
          this.recognizeCalorie(res.tempImagePath);
        }
      },
      fail: (err) => {
        console.error("拍照失败", err);
        wx.showToast({
          title: "拍照失败，请重试",
          icon: "none",
        });
      },
    });
  },

  // 重新拍摄
  retake() {
    this.setData({
      showCamera: true,
      imagePath: null,
      scanResult: null,
      isScanning: this.data.currentTab === "scan", // 重新拍摄时重置扫码状态
    });

    if (this.data.currentTab === "scan") {
      this.startScan();
    }
  },

  // 热量识别功能
  recognizeCalorie(imagePath) {
    wx.showLoading({
      title: "识别中...",
    });

    // 调用热量识别 API
    // ...

    wx.hideLoading();
  },
});
